/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package crashManager;

import comunications.ClientComunicateImpl;
import comunications.ClientComunicateInterface;
import comunications.Ping;
import comunications.SendDeathNotification;
import comunications.SendTable;
import gameState.Player;
import gameState.Ring;
import gameState.Table;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author DEX
 */
public class CrashManager {

    private Ring ring;
    private Table table;
    Logger logger = Logger.getLogger(this.getClass().getSimpleName());

    public CrashManager(){
        this.ring = Ring.getInstance();
        this.table = Table.getInstance();
        logger.setLevel(Level.ALL);
        logger.info("[CrashManager] il costruttore del monte dice che ring.size(): "+ring.size());
        logger.info("[CrashManager] il costruttore del monte dice che ring.getMe().getName(): "+ring.getMe().getName());
    }


    public void solveNext(){
        ring.stampaRing("stampa richiesta da [crashManager || solveNext]");
        Player nextPlayer = ring.getMyNextPlayer();
            try{
                Registry registry = LocateRegistry.getRegistry(nextPlayer.getIp(), nextPlayer.getPort());
                ClientComunicateInterface cci = (ClientComunicateInterface)registry.lookup("ClientComunicateImpl");
                if(ring.amIalone()){
                    logger.warning("[CrashManager || solveNext] tento di dirmi che son rimasto da solo");
                    table.setVersion(-2);
                    cci.bringTable(table);
                    logger.warning("[CrashManager || solveNext] mi sono detto che son rimasto da solo");
                }
                else{
                cci.areYouALive();
                }
            }
            catch(Exception e){
                logger.warning("[CrashManager || solveNext] exception caught");
                logger.info("[CrashManager || solveNext] scoperto che e' morto "+nextPlayer.getName());
                ring.removePlayer(nextPlayer);
                DeathList dl = DeathList.getInstance();
                dl.addDeathPlayer(nextPlayer);
                try{
                     Thread sdn = new SendDeathNotification();
                     sdn.start();
                }
                catch(Exception e2){
                    logger.warning("[CrashManager || solveNext] lanciata eccezione in SendDeathNotification");
                    e2.printStackTrace();
                }
            }

    }


}
